#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
import random
import time
import numpy as np
import requests
from PIL import ImageGrab
import paddleocr
import logging
import Tools
import cv2
import imgDraw as img_obj
import tkinter
import threading

logging.disable(logging.DEBUG)  # 关闭DEBUG日志的打印
logging.disable(logging.WARNING)  # 关闭WARNING日志的打印

class logic:
    username = "MYKfarm32" # 账户名称
    url_get_account = "http://h5.elex-tech.com/a12/api2.php?name={}" # 获取账户id
    url_get_red_packet = "http://h5.elex-tech.com/a12/api.php?a=1&id={}&code={}" # 领取福利
    account_id = None # 账户id
    code_arr = [] # code列表
    ocr_str = [] # 识别内容
    window_point = [0, 0, 0, 0] # 坐标
    sleep_time = 1.2 # 截屏秒数
    ui = None # ui对象
    stop = False # 是否停止运行
    str_ocr_len = 0 # 识别条数
    runGrabWindow_status = False
    root_tk = None


    def __init__(self, ui):
        self.ui = ui # 页面操作
        # 启动paddle-ocr
        self.paddleocr_obj = paddleocr.PaddleOCR(enable_mkldnn=True, use_tensorrt=True, use_angle_cls=False, use_gpu=False)
        self.root_tk = tkinter.Tk()
        self.root_tk.withdraw()
        width = self.root_tk.winfo_screenwidth()
        height = self.root_tk.winfo_screenheight()
        self.window_W_H = (width, height)
        pass

    """
        截屏，并进行转ocr操作
    """
    def runGrabWindow(self):
        # 未选择坐标，不能做操作
        if tuple(self.window_point) == (0, 0, 0, 0):
            print('操作fals1e111')
            return False
        while True:
            if self.stop is True:
                print('操作false')
                return False
            self.runGrabWindow_status = True
            # 截屏
            img = self.getGrabImg(tuple(self.window_point))
            # 图片进行ocr识别内容数据
            self.getOcrData(img)
            time.sleep(float(self.sleep_time))
            self.runGrabWindow_status = False
        pass
    pass


    """
        获取截图
    """
    def getGrabImg(self, bbox):
        img = ImageGrab.grab(bbox=bbox)  # bbox 定义左、上、右和下像素的4元组
        # 图片转数组
        img = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 3)
        return img

    """
        ocr识别结果，并返回相关内容
    """
    def getOcrData(self, img):
        try:
            result = self.paddleocr_obj.ocr(img, cls=True)
            for v in result:
                # 获取文字内容，并向过滤方法操作数据
                try:
                    self.filterStr(v[1][0])
                    pass
                except BaseException as e:
                    pass
                pass
            pass
        except BaseException as e:
            print(e)
            return False
        pass

    """
        过滤字符串，过滤完成后向接口发送请求
    """
    def filterStr(self, strval):
        strip_str = strval.replace(" ", "") # 去除空格
        if strip_str not in self.ocr_str:
            self.str_ocr_len += 1
            pass
            threading_obj = threading.Thread(target=self.moveCursor, args=(3, strip_str,))
            threading_obj.start()
            self.ocr_str.append(strip_str) # 添加识别内容
        else:
            return Tools.returnMsg('1', {'str': strval}, '字符串已操作过')
            pass
        if strip_str.isalnum() is False:
            return Tools.returnMsg('1', {'str': strval}, '字符串非福利码')
            pass
        if len(strip_str) < 7:
            return Tools.returnMsg('1', {'str': strval}, '字符串非福利码')
            pass
        # 尝试领取
        res = self.sendRedPacket(strip_str)
        str_res = "兑换码：{} {}"
        if res['code'] == '0':
            str_res = str_res.format(strip_str, '领取成功')
            pass
        else:
            str_res = str_res.format(strip_str, res['msg'])
            pass
        threading_obj = threading.Thread(target=self.moveCursor, args=(4, str_res,))
        threading_obj.start()
        pass

    """
        识别滑动
    """
    def moveCursor(self, id=3, strval=''):
        if id == 3:
            self.ui.textBrowser_3.append(strval)
            self.ui.textBrowser_3.moveCursor(self.ui.textBrowser_3.textCursor().End)  # 文本框显示到底部
        if id == 4:
            self.ui.textBrowser_4.append(strval)
            self.ui.textBrowser_4.moveCursor(self.ui.textBrowser_4.textCursor().End)  # 文本框显示到底部
        pass

    """
        获取账户id
    """
    def getAccount(self, username):
        res = requests.get(self.url_get_account.format(username))
        try:
            res_json = json.loads(res.text)
            self.account_id = res_json['id']
            print(res_json)
            if res_json['id'] == '':
                return Tools.returnMsg('1', '错误', '账户不存在')
            return Tools.returnMsg(0, res_json)
            pass
        except BaseException as e:
            return Tools.returnMsg('1', '错误', '账户不存在')
            pass
        pass

    """
        领取福利
        code -- 礼包码
    """
    def sendRedPacket(self, code=''):
        if self.account_id is None:
            return Tools.returnMsg('1', '', '账户不存在')
        if code == '':
            return Tools.returnMsg('1', '', '礼包码不存在')
        if code in self.code_arr:
            return Tools.returnMsg('1', {
                    'code': code
                }, '礼包码已请求过')
        self.code_arr.append(code) # 追加请求
        res = requests.get(self.url_get_red_packet.format(self.account_id, code)) # 向接口请求数据
        try:
            json_de = json.loads(res.text)
            if json_de['status'] > 10001:
                return Tools.returnMsg(json_de['status'], {
                    'code': code
                }, '错误码')
                pass
            else:
                pass
                return Tools.returnMsg('0', {
                    'code': code
                }, 'success')
            pass
        except BaseException as e:
            return Tools.returnMsg('1', {'e': str(e)}, '请求错误')
            pass
        pass

    """
        获取屏幕选取坐标
    """
    def getWindowPoint(self):
        img_obj.is_over = False
        img = self.getGrabImg((0, 0, self.window_W_H[0], self.window_W_H[1]))
        img_obj.startRoi(img)
        self.window_point = img_obj.g_rectangle
        return img_obj.g_rectangle

    pass

if __name__ == '__main__':
    obj = logic()
    # obj.getWindowPoint()
    # cv2.imshow('', img)
    # cv2.waitKey(0)
    pass